#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

//"w"  "r"  "a"
_FILE* _fopen(const char* filename, const char* mode)
{
    assert(filename);
    assert(mode);
    int f = 0;
    int fd = -1;
    if(strcmp(mode, "w") == 0)
    {
        f = (O_WRONLY|O_CREAT|O_TRUNC);
        fd = open(filename, f, FILE_MODE);
    }
    else if(strcmp(mode, "r") == 0)
    {
        f = (O_RDONLY);
        fd = open(filename, f, FILE_MODE);
        
    }
    else if(strcmp(mode, "a") == 0)
    {
        f = (O_WRONLY|O_CREAT|O_APPEND);
        fd = open(filename, f, FILE_MODE);

    }
    else 
    {
        return NULL;
    }

    if(fd == -1)  return NULL;
    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
    
    fp->fileno = fd;
    //fp->flag = FLUSH_NOW;
    fp->flag = FLUSH_ALL;
    fp->outpos = 0;

    return fp;

}


int _fwrite(_FILE* fp, const char* s, int len)
{
    memcpy(&fp->outbuffer[fp->outpos], s, len);
    fp->outpos += len;
    if(fp->flag == FLUSH_NOW)
    {
        write(fp->fileno, fp->outbuffer, fp->outpos);
        fp->outpos = 0;
    }
    else if(fp->flag == FLUSH_LINE)
    {
        if(fp->outbuffer[fp->outpos - 1] == '\n')
        {
            write(fp->fileno, fp->outbuffer, fp->outpos);
            fp->outpos = 0;

        }
    }
    else if(fp->flag == FLUSH_ALL)
    {
        if(fp->outpos == SIZE)
        {
            write(fp->fileno, fp->outbuffer, fp->outpos);
            fp->outpos = 0;
        }
    }

    return len;
}

void _fflush(_FILE* fp)
{
    write(fp->fileno, fp->outbuffer, fp->outpos);
    fp->outpos = 0;

}
void _fclose(_FILE* fp)
{
    if(fp == NULL)  return;
    if(fp->outpos > 0)
    {
        _fflush(fp);
    }
    close(fp->fileno);
    free(fp);
}
